<?php

define('DOCTYPE_CUST', 1);
define('DOCTYPE_LOC', 2);
define('DOCTYPE_DISPATCH', 3);
define('STATUS_NEW', 1);
define('STATUS_JUSTADDED', 2);
define('STATUS_OLD', 3);

function sort_array_by_mktime($a, $b)
{

    if ($a['mktime'] == $b['mktime'])
    {
        return 0;
    }
    return ($a['mktime'] < $b['mktime']) ? -1 : 1;
}

function safeExplode($delimiter,$line){
    $lineArray = array();
    $lastPost = 0;
    $hasQuote = false;    
    $i = 0;
    while ($i < strlen($line) - 1)
    {
        $char = substr($line, $i, 1);
        if ($char == '"')
        {
            if ($hasQuote)
            {
                $lineArray[] = substr($line, $lastPost, $i - $lastPost);
                $lastPost = $i + 2;
                $i+=2;
                $hasQuote = false;
            }
            else
            {
                $hasQuote = true;
                $lastPost = $i + 1;
                $i+=1;
            }
        }
        elseif ($char == $delimiter && $hasQuote == false)
        {
            $lineArray[] = substr($line, $lastPost, $i - $lastPost);
            $lastPost = $i + 1;
            $i++;
        }
        else
        {
            $i++;
            if($i==strlen($line)-1){
                $lineArray[] = substr($line, $lastPost);
            }
        }
    }
    return $lineArray;
}
/*
 * get max number of a field in table
 * useful for increment value
 */
function getIncrementNumber($table, $column, $condition=NULL, $params=NULL)
{
    $sql = "select max(cast($column as unsigned)) from $table";
    if ($condition != NULL)
    {
        $sql.=' ' . $condition;
    }

    $cmd = Yii::app()->db->createCommand($sql);
    if ($params != NULL)
    {
        $cmd->bindValues($params);
    }
    $data = $cmd->queryScalar();
    if ($data !== false && $data != NULL)
    {

        return $data;
    }
    return 0;
}

/*
 * Create an id like e5d3e848-c93e-4958-956e-06601b1bfc2a, length = 36
 */

function createRandomUUID()
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    mt_srand(time());
    $rs         = '';
    $length     = 36;
    for ($i = 0; $i < $length; $i++)
    {
        if ($i == 8 || $i == 8 + 4 || $i == 12 + 4 || $i == 12 + 4 + 4)
        {
            $rs.='-';
        }
        else
        {
            $rs.=$characters[mt_rand(0, strlen($characters) - 1)];
        }
    }
    return $rs;
}

//convert from db date to your format
function convertDate($format, $date)
{
    if ($date != null)
    {
        $time = strtotime($date);
        if ($time !== false)
        {
            return date($format, $time);
        }
    }
    return '';
}

function createRandomString($length)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    mt_srand();
    $rs         = '';
    for ($i = 0; $i < $length; $i++)
    {
        $rs.=$characters[mt_rand(0, strlen($characters) - 1)];
    }
    return $rs;
}

function outputJsVarible($value, $variableName)
{
    $rand = rand(0, 9999999);
    Yii::app()->clientScript->registerScript("$rand", "var $variableName='$value';", CClientScript::POS_HEAD);
}

function outputJsByList($list, $variableName, $arrayStore=false)
{
    $rs = array();

    if (is_array($list) && count($list) > 0)
    {
        $count = 0;
        foreach ($list as $i => $item)
        {
            if (!$arrayStore)
            {
                $rs[] = array(
                    'key' => "$i",
                    'value' => $item
                );
            }
            else
            {
                $rs[] = array("$i", $item);
            }
        }
    }
    $rand = rand(0, 9999999);
    $rs = json_encode($rs);
    Yii::app()->clientScript->registerScript($rand, "var $variableName=$rs;", CClientScript::POS_HEAD);
}

function encrypt($data)
{

    return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, '123', $data, MCRYPT_MODE_CFB);
}

function decrypt($encrypted)
{

    $binenc     = base64_encode($encrypted);
    $bstrenc    = base64_decode($binenc);
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, '123', $binenc, MCRYPT_MODE_CFB);
}

function create_slug($str)
{
    $str = trim($str);

    // replace space by -
    $str = preg_replace('/\s+/i', '-', $str);

    return $str;
}

function getImage($name, $folder, $width, $height)
{

    if (trim($name) == '' || !file_exists($folder))
    {

        return getImageBySize(Yii::app()->params['noImage'], $width, $height, false);
    }
    else
    {

        if (substr($folder, strlen($folder) - 1, 1) != '/')
        {
            $folder.='/';
        }
        if (!file_exists($folder . $name))
        {
            return getImageBySize(Yii::app()->params['noImage'], $width, $height, false);
        }
        return getImageBySize($folder . $name, $width, $height, false);
    }
}

function getImageBySize($path=NULL, $width=128, $height=128, $addPath=true)
{
    if (!isset($path) || $path == '' || trim($path == ''))
    {
        return getImageBySize(Yii::app()->params['noImage'], $width, $height, false);
    }
    if ($addPath)
        $path = 'images/content/' . $path;

    $ext        = getFileExt($path);
    clearstatcache();
    $directory  = substr($path, 0, strlen($path) - strlen($ext));
    $fullPath   = $directory . "_{$width}x{$height}" . $ext;


    if (file_exists($fullPath))
    {
        return $fullPath;
    }
    else
    {

        if (file_exists($path))
        {

            $img = Yii::app()->simpleImage->load($path);
            if ($img->getWidth() > $width)
            {
                $img->resizeToWidth($width);
                $img->save($fullPath);
                return $fullPath;
            }
            else
            {
                return $path;
            }
        }
    }
}

function getFileBodyName($name)
{
    $pos = stripos($name, ".");
    if ($pos)
    {
        return substr($name, 0, $pos);
    }
    else
    {
        return "";
    }
}

function getFileExt($name)
{
    $pos = stripos($name, ".");
    if ($pos)
    {
        return substr($name, $pos);
    }
    else
    {
        return "";
    }
}

function dbDateToHumanTiming($date)
{
    if (empty($date))
        return;
    return humanTiming(dbDateToTime($date));
}

function humanTiming($time)
{

    $time = time() - $time; // to get the time since that moment

    $tokens = array(
        31536000    => 'year',
        2592000     => 'month',
        604800      => 'week',
        86400       => 'day',
        3600        => 'hour',
        60          => 'minute',
        1           => 'second'
    );

    foreach ($tokens as $unit => $text)
    {
        if ($time < $unit)
            continue;
        $numberOfUnits = floor($time / $unit);

        return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
    }
}

function stripExtraSpace($string)
{
    return preg_replace("/\s+/", " ", $string);
}

function limitWord($str, $limit)
{
    $words  = explode(' ', stripExtraSpace($str));
    $result = "";
    $i      = 0;
    foreach ($words as $word)
    {
        $i++;
        $result.=$word;
        if ($i >= $limit)
            break;
    }
    return $result;
}

function dbDateToTime($date)
{
    $datetime   = explode(' ', $date);
    $date       = explode('-', $datetime[0]);
    $time       = explode(':', $datetime[1]);
    if (!empty($time))
    {
        return mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
    }
    else
    {
        return mktime(0, 0, 0, $date[1], $date[2], $date[0]);
    }
}

function getUserByPermission($permission)
{
    $users  = Yii::app()->db->createCommand('select u.email from tbl_useraccess ua 
        join tbl_users u on u.id=ua.user_id
        where find_in_set(:permission,ua.privilege)>0')->bindValues(array(
                'permission' => $permission
            ))->queryAll();


    $rs     = array();
    $s      = '';
    if ($users != NULL && count($users > 0))
    {
        foreach ($users as $i => $item)
        {

            $s.=$item['email'] . ',';
        }
    }

    $rs = explode(',', $s);
    return $rs;
}

function isDateValid($date)
{
    return (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date));
}

function getStateList()
{
    return array(
        'AL' => 'AL',
        'AK' => 'AK',
        'AZ' => 'AZ',
        'AR' => 'AR',
        'CA' => 'CA',
        'CO' => 'CO',
        'CT' => 'CT',
        'DE' => 'DE',
        'FL' => 'FL',
        'GA' => 'GA',
        'HI' => 'HI',
        'ID' => 'ID',
        'IL' => 'IL',
        'IN' => 'IN',
        'IA' => 'IA',
        'KS' => 'KS',
        'KY' => 'KY',
        'LA' => 'LA',
        'ME' => 'ME',
        'MD' => 'MD',
        'MA' => 'MA',
        'MI' => 'MI',
        'MN' => 'MN',
        'MS' => 'MS',
        'MO' => 'MO',
        'MT' => 'MT',
        'NE' => 'NE',
        'NV' => 'NV',
        'NH' => 'NG',
        'NJ' => 'NJ',
        'NM' => 'NM',
        'NY' => 'NY',
        'NC' => 'NC',
        'ND' => 'ND',
        'OH' => 'OH',
        'OK' => 'OK',
        'OR' => 'OR',
        'PA' => 'PA',
        'PR' => 'PR',
        'RI' => 'RI',
        'SC' => 'SC',
        'SD' => 'SD',
        'TN' => 'TN',
        'TX' => 'TX',
        'UT' => 'UT',
        'VT' => 'VT',
        'VA' => 'VA',
        'WA' => 'WA',
        'WV' => 'WV',
        'WI' => 'WI',
        'WY' => 'WY',
    );
}

function getUserRealname($email)
{
    $name = Yii::app()->db->createCommand('select real_name from tbl_users where email=:email')->bindParam('email', $email)->queryScalar();
    if ($name != false)
    {
        return $name;
    }
    else
    {
        return NULL;
    }
}

function resize($img, $w, $h, $newfilename)
{

    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2'))
    {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }

    //Get Image size info
    $imgInfo = getimagesize($img);
    switch ($imgInfo[2])
    {
        case 1: $im = imagecreatefromgif($img);
            break;
        case 2: $im = imagecreatefromjpeg($img);
            break;
        case 3: $im = imagecreatefrompng($img);
            break;
        default: trigger_error('Unsupported filetype!', E_USER_WARNING);
            break;
    }

    //If image dimension is smaller, do not resize
    if ($imgInfo[0] <= $w && $imgInfo[1] <= $h)
    {
        $nHeight = $imgInfo[1];
        $nWidth = $imgInfo[0];
    }
    else
    {
        //yeah, resize it, but keep it proportional
        if ($w / $imgInfo[0] > $h / $imgInfo[1])
        {
            $nWidth     = $w;
            $nHeight    = $imgInfo[1] * ($w / $imgInfo[0]);
        }
        else
        {
            $nWidth     = $imgInfo[0] * ($h / $imgInfo[1]);
            $nHeight    = $h;
        }
    }
    $nWidth     = round($nWidth);
    $nHeight    = round($nHeight);
    $newImg     = imagecreatetruecolor($nWidth, $nHeight);

    /* Check if this image is PNG or GIF, then set if Transparent */
    if (($imgInfo[2] == 1) OR ($imgInfo[2] == 3))
    {
        imagealphablending  ($newImg, false);
        imagesavealpha      ($newImg, true);
        $transparent        = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

    //Generate the file, and rename it to $newfilename
    switch ($imgInfo[2])
    {
        case 1: imagegif($newImg, $newfilename);
            break;
        case 2: imagejpeg($newImg, $newfilename);
            break;
        case 3: imagepng($newImg, $newfilename);
            break;
        default: trigger_error('Failed resize image!', E_USER_WARNING);
            break;
    }

    return $newfilename;
}
